/* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 
Copyright (C) 2010 by Tomasz Pluskiewicz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */

using Castle.Core.Configuration;
using Castle.MonoRail.Framework;

namespace Yama.MVC.MonoRail.Extensions
{
    /// <summary>
    /// This extension evaluates incoming requests and by default persists the  result between redirects in
    /// Flash['is.ajax'].
    /// </summary>
    /// To successfully install this extension you must at least register
    /// it on the <c>extensions</c> node and (optionally) the headers within the <c>extension</c> node.
    /// 
    /// This is based on http://using.castleproject.org/display/MR/Handling+Ajax+Requests
    /// <code>
    ///   &lt;monorail&gt;
    ///   	&lt;extensions&gt;
    ///   	  &lt;extension type="Cei.Phoenix.Web.Controller.Extensions.AjaxRequestExtension, Cei.Phoenix.Web.Controller" /&gt;
    ///   	&lt;/extensions&gt;
    ///   &lt;/monorail&gt;
    /// </code>
    public class AjaxRequestExtension : IMonoRailExtension
    {
        private const string DefaultHeaderKey = "X-Requested-With";
        private const string DefaultHeaderValue = "XMLHttpRequest";
        private const string DefaultPrefetchHeader = "X-moz";
        private const string DefaultPrefetchValue = "prefetch";

        #region IMonoRailExtension Members

        public void SetExtensionConfigNode(IConfiguration node)
        {
        }

        public void Service(IMonoRailServices serviceProvider)
        {
            ExtensionManager manager = (ExtensionManager)
                                       serviceProvider.GetService(typeof(ExtensionManager));

            manager.PreControllerProcess += PreControllerProcess;
            manager.PostControllerProcess += PostControllerProcess;
            manager.UnhandledException += ProcessUnhandledException;
        }

        #endregion

        protected virtual void PreControllerProcess(IEngineContext context)
        {
            ProcessContext(context);
        }

        protected virtual void PostControllerProcess(IEngineContext context)
        {
            CleanUp(context);
        }

        protected virtual void ProcessUnhandledException(IEngineContext context)
        {
            CleanUp(context);
        }

        /// <summary>
        /// Template for evaluating and setting the header discovery within a request.
        /// </summary>
        /// <param name="engineContext"></param>
        protected virtual void ProcessContext(IEngineContext engineContext)
        {
            bool shouldInspect = ShouldInspectHeadersForAjax(engineContext);
            bool isAjax = !shouldInspect ? PreviousRequestWasAjax(engineContext) : RequestHasAjaxHeader(engineContext);

            AjaxContextAdapter.IsAjax = isAjax;
        }

        /// <summary>
        /// If previous ajax evaluation results are persisted (by default in Flash) then no further evaluation will
        /// be done to accomodate redirects within an ajax call.
        /// </summary>
        /// <param name="engineContext"></param>
        /// <returns></returns>
        protected virtual bool PreviousRequestWasAjax(IEngineContext engineContext)
        {
            bool isAjax = AjaxContextAdapter.IsAjax;
            return isAjax;
        }

        /// <summary>
        /// Determines if the headers should be searched for ajax headers. Firefox doesnt persist
        /// Xhttp headers between redirects, requiring us to persist the evaluation on our own.
        /// </summary>
        /// <param name="engineContext"></param>
        /// <returns></returns>
        protected virtual bool ShouldInspectHeadersForAjax(IEngineContext engineContext)
        {
            return !engineContext.Flash.ContainsKey(AjaxContextAdapter.IsAjaxKey);
        }

        /// <summary>
        /// Searches request headers for at least one of the key/value pairs specified in config (optional)
        /// or the default 'X-Requested-With/XMLHttpRequest' pair.
        /// </summary>
        /// <param name="engineContext"></param>
        /// <returns></returns>
        protected virtual bool RequestHasAjaxHeader(IEngineContext engineContext)
        {
            return engineContext.Request.Headers[DefaultHeaderKey] == DefaultHeaderValue
                   && (engineContext.Request.Headers[DefaultPrefetchHeader] != DefaultPrefetchValue);
        }

        /// <summary>
        /// Cleans up the flash entry if the last response wasn't a redirect.
        /// </summary>
        /// <param name="engineContext"></param>
        protected virtual void CleanUp(IEngineContext engineContext)
        {
            if (!engineContext.Response.WasRedirected)
            {
                if (engineContext.Flash != null)
                    engineContext.Flash.Remove(AjaxContextAdapter.IsAjaxKey);
            }
        }
    }
}